import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;


public class CMain {

	public static void main(String[] p){
		
		try {
			ServerSocket server=new ServerSocket(1022);
			System.out.println("Server is started.  IP:"+
					Inet4Address.getLocalHost().getHostAddress());
			ArrayList<CMessage> list=new 	ArrayList<CMessage>();
			
			
			while(true){
				Socket client = server.accept();
				System.out.println("Client is connected.");
				DataInputStream streamIn=
					new DataInputStream(client.getInputStream());
				String strData=streamIn.readUTF();
				System.out.println(strData);
				String[] strItems=strData.split("\t");
				
				CMessage msg=new CMessage(strItems[0],
						strItems[1],strItems[2],false);
				
				for(CMessage m : list){
					if(m.GetTo().equals(msg.GetFrom())&&
							!m.GetIsRead()){
						m.SetIsRead(true);
						DataOutputStream streamOut=
							new DataOutputStream(client.getOutputStream());
						streamOut.writeUTF(m.GetFrom()+":"+m.GetMessage());
						streamOut.close();
						client.close();
						break;
					}
				}
				if(!".".equals(msg.GetMessage()))
					list.add(msg);
				client.close();
					
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
